#include <tinyalsa/asoundlib.h>

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <endian.h>
#include <unistd.h>

#define ID_RIFF 0x46464952
#define ID_WAVE 0x45564157
#define ID_FMT  0x20746d66
#define ID_DATA 0x61746164

typedef enum {false = 0, true = 1} bool;

enum PlayStatus {
    PLAY_STATUS_DEFAULT = 0,
    PLAY_STATUS_PLAYING = 1,
    PLAY_STATUS_STOPPED = 2,
    PLAY_STATUS_ERROR
};

#define STRINGIZE(x) #x

#define AP_SIGNAL_PLAY_STATUS (55)
#define AP_SIGNAL_CONTROL_PAUSE (56)
#define AP_SIGNAL_CONTROL_SEEK (57)

#define AP_SIGNAL_FRAME_COUNT (60)
#define AP_SIGNAL_CURRENT_SECONDS (61)


static const char* ctl2str(int ctl) {
    switch(ctl){
    case AP_SIGNAL_PLAY_STATUS:
        return STRINGIZE(AP_SIGNAL_PLAY_STATUS);
    case AP_SIGNAL_CONTROL_PAUSE:
        return STRINGIZE(AP_SIGNAL_CONTROL_PAUSE);
    case AP_SIGNAL_CONTROL_SEEK:
        return STRINGIZE(AP_SIGNAL_CONTROL_SEEK);
    default:
        return "";
    }
}

struct riff_wave_header {
    uint32_t riff_id;
    uint32_t riff_sz;
    uint32_t wave_id;
};

struct chunk_header {
    uint32_t id;
    uint32_t sz;
};

struct chunk_fmt {
    uint16_t audio_format;
    uint16_t num_channels;
    uint32_t sample_rate;
    uint32_t byte_rate;
    uint16_t block_align;
    uint16_t bits_per_sample;
};

#undef TAG
#define TAG "BOSECMD_PLAY"
#ifdef __ANDROID__
#include <android/log.h>
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#else
#define LOGI(str, ...) do{printf("BOSECMD_PLAY ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define LOGD(str, ...) do{printf("BOSECMD_PLAY ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define LOGW(str, ...) do{printf("BOSECMD_PLAY ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#define LOGE(str, ...) do{printf("BOSECMD_PLAY ");printf(str,##__VA_ARGS__);printf("\n");}while(0)
#endif

#define MAX_RETRY_TIMES (5)

static int isClosing = 0;

bool g_pausing = false;
int32_t g_seek_seconds = 0;

void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int channels,
                 unsigned int rate, unsigned int bits, unsigned int period_size,
                 unsigned int period_count, uint32_t data_sz);

void stream_close(int sig) {
    /* allow the stream to be closed gracefully */
    signal(sig, SIG_IGN);
    isClosing = 1;
}

int main(int argc, char const * argv[]) {
    FILE *file;
    struct riff_wave_header riff_wave_header;
    struct chunk_header chunk_header;
    struct chunk_fmt chunk_fmt;
    unsigned int device = 0;
    unsigned int card = 0;
    unsigned int period_size = 1024;
    unsigned int period_count = 4;
    const char *filename;
    int more_chunks = 1;

    if (argc < 2) {
        LOGI("Usage: %s file.wav [-D card] [-d device] [-p period_size]"
                " [-n n_periods] \n", argv[0]);
        return 1;
    }

    filename = argv[1];
    file = fopen(filename, "rb");
    if (!file) {
        LOGE("Unable to open file '%s'\n", filename);
        return 1;
    }

    fread(&riff_wave_header, sizeof(riff_wave_header), 1, file);
    if ((riff_wave_header.riff_id != ID_RIFF) ||
        (riff_wave_header.wave_id != ID_WAVE)) {
        LOGI("Error: '%s' is not a riff/wave file\n", filename);
        fclose(file);
        return 1;
    }

    do {
        fread(&chunk_header, sizeof(chunk_header), 1, file);

        switch (chunk_header.id) {
        case ID_FMT:
            fread(&chunk_fmt, sizeof(chunk_fmt), 1, file);
            /* If the format header is larger, skip the rest */
            if (chunk_header.sz > sizeof(chunk_fmt))
                fseek(file, chunk_header.sz - sizeof(chunk_fmt), SEEK_CUR);
            break;
        case ID_DATA:
            /* Stop looking for chunks */
            more_chunks = 0;
            chunk_header.sz = le32toh(chunk_header.sz);
            break;
        default:
            /* Unknown chunk, skip bytes */
            fseek(file, chunk_header.sz, SEEK_CUR);
        }
    } while (more_chunks);

    /* parse command line arguments */
    argv += 2;
    while (*argv) {
        if (strcmp(*argv, "-d") == 0) {
            argv++;
            if (*argv)
                device = atoi(*argv);
        }
        if (strcmp(*argv, "-p") == 0) {
            argv++;
            if (*argv)
                period_size = atoi(*argv);
        }
        if (strcmp(*argv, "-n") == 0) {
            argv++;
            if (*argv)
                period_count = atoi(*argv);
        }
        if (strcmp(*argv, "-D") == 0) {
            argv++;
            if (*argv)
                card = atoi(*argv);
        }
        if (*argv)
            argv++;
    }

    play_sample(file, card, device, chunk_fmt.num_channels, chunk_fmt.sample_rate,
                chunk_fmt.bits_per_sample, period_size, period_count, chunk_header.sz);

    fclose(file);

    return 0;
}

int check_param(struct pcm_params *params, unsigned int param, unsigned int value,
                 char *param_name, char *param_unit) {
    unsigned int min;
    unsigned int max;
    int is_within_bounds = 1;

    min = pcm_params_get_min(params, param);
    if (value < min) {
        LOGE("%s is %u%s, device only supports >= %u%s\n", param_name, value,
                param_unit, min, param_unit);
        is_within_bounds = 0;
    }

    max = pcm_params_get_max(params, param);
    if (value > max) {
        LOGE("%s is %u%s, device only supports <= %u%s\n", param_name, value,
                param_unit, max, param_unit);
        is_within_bounds = 0;
    }

    return is_within_bounds;
}

int sample_is_playable(unsigned int card, unsigned int device, unsigned int channels,
                        unsigned int rate, unsigned int bits, unsigned int period_size,
                        unsigned int period_count) {
    struct pcm_params *params;
    int can_play;

    params = pcm_params_get(card, device, PCM_OUT);
    if (params == NULL) {
        LOGE("Unable to open PCM device %u.\n", device);
        return 0;
    }

    can_play = check_param(params, PCM_PARAM_RATE, rate, "Sample rate", "Hz");
    can_play &= check_param(params, PCM_PARAM_CHANNELS, channels, "Sample", " channels");
    can_play &= check_param(params, PCM_PARAM_SAMPLE_BITS, bits, "Bitrate", " bits");
    can_play &= check_param(params, PCM_PARAM_PERIOD_SIZE, period_size, "Period size", " frames");
    can_play &= check_param(params, PCM_PARAM_PERIODS, period_count, "Period count", " periods");

    pcm_params_free(params);

    return can_play;
}

static void tinyply_sigaction_function(int signal, siginfo_t* pInfo, void* pvo) {
    int res = pInfo->si_int;
    (void)pvo;
    switch(signal) {
        case AP_SIGNAL_CONTROL_PAUSE:
            if(res == 1) g_pausing = true;
            else if(res == 0) g_pausing = false;
            LOGW("Receive signal AP_SIGNAL_PLAY_CONTROL:%s", ctl2str(res));
            return;
        case AP_SIGNAL_CONTROL_SEEK:
            LOGW("Receive signal AP_SIGNAL_CONTROL_SEEK:%d", res);
            g_seek_seconds = res;
            return;
        default:        //other singals
            LOGE("Received signal 0x%X, exiting...", signal);
            return;
    }
}

void play_sample(FILE *file, unsigned int card, unsigned int device, unsigned int channels,
                 unsigned int rate, unsigned int bits, unsigned int period_size,
                 unsigned int period_count, uint32_t data_sz) {
    struct pcm_config config;
    struct pcm *pcm;
    char *buffer;
    unsigned int size = 0, read_sz;
    int num_read;
    uint32_t frame_count = 0; //bose add
    uint32_t loop_times = 0;
    union sigval play_sig_value; //bose add
    play_sig_value.sival_int = PLAY_STATUS_PLAYING;
    bool called_pause = false;
    uint32_t retry_times = MAX_RETRY_TIMES;
    uint32_t byte_rate = 1;
    uint32_t total_seconds = 0;
    uint32_t current_seconds = 0;

    memset(&config, 0, sizeof(config));
    config.channels = channels;
    config.rate = rate;
    config.period_size = period_size;
    config.period_count = period_count;
    if (bits == 32)
        config.format = PCM_FORMAT_S32_LE;
    else if (bits == 24)
        config.format = PCM_FORMAT_S24_3LE;
    else if (bits == 16)
        config.format = PCM_FORMAT_S16_LE;
    config.start_threshold = 0;
    config.stop_threshold = 0;
    config.silence_threshold = 0;

    do {
        if (!sample_is_playable(card, device, channels, rate, bits, period_size, period_count)) {
            play_sig_value.sival_int = PLAY_STATUS_ERROR;
            LOGE("sample is not playable");
            break;
        }

        pcm = pcm_open(card, device, PCM_OUT, &config);
        if (!pcm || !pcm_is_ready(pcm)) {
            LOGE("Unable to open PCM device %u (%s)\n",
                    device, pcm_get_error(pcm));
            play_sig_value.sival_int = PLAY_STATUS_ERROR;
            break;
        }

        size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
        buffer = (char*)malloc(size);
        if (!buffer) {
            LOGE("Unable to allocate %d bytes\n", size);
            free(buffer);
            pcm_close(pcm);
            play_sig_value.sival_int = PLAY_STATUS_ERROR;
            break;
        }
    } while(0);

    byte_rate = (uint32_t) ((channels * rate * bits) / 8);
    total_seconds = (uint32_t)(data_sz / byte_rate);

    sigqueue(getppid(), AP_SIGNAL_PLAY_STATUS, play_sig_value);

    LOGD("Playing sample: %u ch, %u hz, %u bit %u bytes. read_size=%d, byte_rate=%u, total %u seconds",
                       channels, rate, bits, data_sz, size, byte_rate, total_seconds);

    /* catch ctrl-c to shutdown cleanly */
    signal(SIGINT, stream_close);

    struct sigaction act;
    act.sa_sigaction = tinyply_sigaction_function;
    act.sa_flags = SA_SIGINFO;
    sigaction(AP_SIGNAL_CONTROL_PAUSE, &act, NULL);
    sigaction(AP_SIGNAL_CONTROL_SEEK, &act, NULL);

    play_sig_value.sival_int = PLAY_STATUS_PLAYING;
    sigqueue(getppid(), AP_SIGNAL_PLAY_STATUS, play_sig_value);

    do {
        // bose: send frame counts to parent begin
        uint32_t t = total_seconds - data_sz / byte_rate;
        if ((t - current_seconds) >= 1) {
            current_seconds = t;
            union sigval value;
            value.sival_int = current_seconds;
            sigqueue(getppid(), AP_SIGNAL_CURRENT_SECONDS, value);
            //LOGD("%s. Played %d seconds, [%d]bytes remain.", g_pausing ? "PAUSING" : "PLAYING", current_seconds, data_sz);
        }

        if(g_seek_seconds != 0) {
            if(total_seconds > (current_seconds + g_seek_seconds) && (current_seconds + g_seek_seconds) > 0 ) {
                int32_t seek_bytes = byte_rate * g_seek_seconds;
                seek_bytes -= seek_bytes % size;
                LOGD("Seek to second: %d, seek bytes=%d",g_seek_seconds, seek_bytes);
                fseek(file, seek_bytes, SEEK_CUR);
                data_sz -= seek_bytes;
            }
            g_seek_seconds = 0;
        }

        if(g_pausing) {
            if(!called_pause) {
                called_pause = true;
                pcm_wait(pcm, -1);
            }
            usleep(100*1024);
            continue;
        }
        called_pause = false;
        // bose: send frame counts to parent end

        read_sz = size < data_sz ? size : data_sz;
        num_read = fread(buffer, 1, read_sz, file);
        if (num_read > 0) {
            if (pcm_write(pcm, buffer, num_read)) {
                LOGE("Error playing sample, remain bytes=%d, loop=%d", data_sz, loop_times);
                // receiving signal may interrupt some system call.
                if(    /*g_pausing && */ 
                        retry_times > 0) {
                    continue;
                    retry_times --;
                }
                break;
            }
            retry_times = MAX_RETRY_TIMES;
            frame_count++;
            data_sz -= num_read;
        }
    } while (!isClosing && num_read > 0 && data_sz > 0);

    play_sig_value.sival_int = PLAY_STATUS_STOPPED;
    sigqueue(getppid(), AP_SIGNAL_PLAY_STATUS, play_sig_value);
    free(buffer);
    pcm_close(pcm);
}
